var express = require('express');
var db = require('../config/db')
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
	console.log('as')
	db.query('select * from products ORDER BY salePrice limit 4 ').then(json=>{
		console.log(json);
		res.json({"result":{message:"success",list:json}});
	}).catch(e=>{
		console.log('fail')
	})
	return
});

router.get('/list',function(req,res){
	var priceLevel=req.query.range;
	var sort = req.query.sort;
	if(priceLevel=='all'){
		db.query('select * from products ORDER By salePrice ?',[sort]).then(data=>{
			res.json({status:200,list:json})
		}).catch(e=>{
			res.json({status:401});
		})
	}else{
		var min,max;
		switch(priceLevel){
			case 0:
				min = 0;max=100;break;
			case 1:
				min:100;max:150;break;
			case 2:
				min:150;max:300;break;
			case 3:
				min:300;max:500;break;
			case 4:
				min:500;max=800;break;
		}
		db.query('select * from products where salePrice between ? and ? ORDER By salePrice ?',[min,max,sort]).then(data=>{
			res.json({status:200,list:json})
		}).catch(e=>{
			res.json({status:400});
		})

	}
})

//购物车新增
router.get('/add',function(req,res){
	var userId =1;//假数据
	var productId =001;// req.query.productId;

	db.query('select * from user where userId = ?',[userId]).then(data=>{
		db.query('select * from cartList where userId =?',[userId]).then(cartList=>{
			var productItem ='';
			cartList.forEach(item=>{
				if(item.productId==productId){
					item.productNum++;
					productItem = item;
				}
			})
			
			if(productItem){
				db.query('update cartList set productNum=? where productId=? and userId =?',[productItem.productNum,userId,productId])
				.then(add=>{
					res.json({status:200,message:'新增成功'})
				}).catch(e=>{
					res.json({status:400});
				})
			}else{
				db.query('select * from products where productId=?',[productId])
				.then(proItem=>{
					console.log(proItem[0]);
					proItem=proItem[0]
					proItem.productNum=1;
					proItem.checked=1;
					proItem.userId=userId;
					db.query('insert into cartList  set ?',[proItem])
					.then(add=>{
						res.json({status:200})
					})
				})
			}
		})
		
	}).catch(e=>{
		res.json({status:400});
	})

})
module.exports = router;
